<?php

namespace App\Http\Controllers\TeacherApi\GradeSubject;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Grades;
use App\Model\Subjects;
use App\Model\UserSubject;

class GradeSubjectController extends Controller
{
    public function get_grade_subject(Request $request,Grades $grades,Subjects $subjects){
    	$type = $request->type;

		switch ($type) {
			case 0:
				$this->data['msg'] = '年级获取成功！';
				$this->data['code'] = 1;
				$this->data['data'] = $grades->get();
				break;
			case 1:
				$this->data['msg'] = '科目获取成功！';
				$this->data['code'] = 1;
				$this->data['data'] = $subjects->get();
				break;
			default:
				$this->data['msg'] = '传的什么鬼！';
				break;
    	}

    	return $this->data;
    }


    // 根据用户id 获取默认选择科目年级
    public function get_default_subject(Request $request,UserSubject $userSubject){
    	$id = $request->id;
    	$rs = $userSubject->where(['is_default'=>1,'user_id'=>$id])->first();
    	if(!empty($rs)){
    		$this->data['code'] = 1;
    		$this->data['msg'] = '默认数据';
    		$this->data['data'] = $rs;
    	}else{
    		$this->data['data']['grade_id'] = 0;
    		$this->data['data']['subject_id'] = 1;
    		$this->data['msg'] = '没有数据';
    	}
    	return $this->data;
    }

    // 设置默认科目年级
    public function setting_default_subject(Request $request,UserSubject $userSubject,Grades $grades,Subjects $subjects){
    	$id = $request->id;
    	$grade = $request->grade;
    	$subject = $request->subject;
    	$question_num = $request->question_num+0;
    	$question_num = $question_num?$question_num:10;

    	$whereInfo = [
    		'user_id'=>$id,
    		'grade_id'=>$grade,
    		'subject_id'=>$subject,
    	];
    	
    	
		$userSubjectInfo = $userSubject->where($whereInfo)->first();

		
		// 查看是否存在这条设置信息
		if(empty($userSubjectInfo)){
			$whereInfo['is_default'] = 1;
			$whereInfo['questions'] = '';
			$whereInfo['errors'] = '';
			$whereInfo['add_time'] = time();
			$whereInfo['question_num'] = $question_num;
			$userSubject->where(['user_id'=>$id])->update(['is_default'=>0]);// 将原来默认的取消
			$rs = $userSubject->insert($whereInfo);
		}else{
			$userSubject->where(['user_id'=>$id])->update(['is_default'=>0]);// 将原来默认的取消
			$status = [
				'is_default'=>1,
				'question_num' => $question_num,
			];
			$rs = $userSubject->where($whereInfo)->update($status);
			$whereInfo['question_num'] = $question_num;
		}

		if($rs){
			$this->data['code'] = 1;
			$this->data['msg'] = '设置成功！';
			$this->data['data'] = $whereInfo;
		}

    	return $this->data;
    }
}
